#!/usr/bin/env python3
"""
Setup script for Roboflow Dataset Downloader

This script helps you set up the project environment.
"""

import os
import sys
import subprocess

def check_python_version():
    """Check if Python version is 3.7 or higher"""
    if sys.version_info < (3, 7):
        print("Error: Python 3.7 or higher is required.")
        print(f"Current version: {sys.version}")
        return False
    print(f"✓ Python version: {sys.version.split()[0]}")
    return True

def install_dependencies():
    """Install required dependencies"""
    print("\nInstalling dependencies...")
    try:
        subprocess.check_call([sys.executable, "-m", "pip", "install", "-r", "requirements.txt"])
        print("✓ Dependencies installed successfully!")
        return True
    except subprocess.CalledProcessError as e:
        print(f"✗ Error installing dependencies: {e}")
        return False

def setup_env_file():
    """Set up the .env file from template"""
    if not os.path.exists('.env'):
        if os.path.exists('.env.example'):
            try:
                with open('.env.example', 'r') as src, open('.env', 'w') as dst:
                    dst.write(src.read())
                print("✓ Created .env file from template")
                print("  Please edit .env and add your Roboflow API key!")
                return True
            except Exception as e:
                print(f"✗ Error creating .env file: {e}")
                return False
        else:
            print("✗ .env.example file not found")
            return False
    else:
        print("✓ .env file already exists")
        return True

def verify_installation():
    """Verify that the installation works"""
    print("\nVerifying installation...")
    try:
        import roboflow
        import dotenv
        print("✓ All required packages are importable")
        
        # Check if .env file has API key
        from dotenv import load_dotenv
        load_dotenv()
        api_key = os.getenv('ROBOFLOW_API_KEY')
        if api_key and api_key != 'your_api_key_here':
            print("✓ API key is configured")
        else:
            print("⚠ API key not configured - please update .env file")
        
        return True
    except ImportError as e:
        print(f"✗ Import error: {e}")
        return False

def main():
    """Main setup function"""
    print("=== Roboflow Dataset Downloader Setup ===\n")
    
    # Check Python version
    if not check_python_version():
        sys.exit(1)
    
    # Install dependencies
    if not install_dependencies():
        sys.exit(1)
    
    # Setup .env file
    if not setup_env_file():
        sys.exit(1)
    
    # Verify installation
    if not verify_installation():
        sys.exit(1)
    
    print("\n=== Setup Complete! ===")
    print("\nNext steps:")
    print("1. Edit .env file and add your Roboflow API key")
    print("2. Get your API key from: https://roboflow.com/")
    print("3. Test the installation by running:")
    print("   python download_dataset.py --list-workspaces")
    print("\nFor usage examples, run:")
    print("   python example.py")

if __name__ == "__main__":
    main()